<template>
  <div class="tabsBox d-flex m-b20">
    <div
      class="tabsItem"
      :class="item.id === state.tabId ? 'tabsItemHover' : ''"
      v-for="item in tabsList"
      :key="item.id"
      @click="selected(item.id)"
    >
      {{ item.name }}
    </div>
  </div>

  <div class="tabsClass">
    <div class="tabBox">
      <tableIndex
        ref="tableRef"
        :tableData="tableData"
        :tableHead="tableHead"
        :isIndex="true"
        :isSelection="true"
        :isRadio="true"
        :fields="state.fields"
        :height="500"
        :page="page"
        @selectChange="selectChange"
        @searchList="searchList"
        @page-change="pageChange"
      >
        <template #btns>
          <div style="float: right">
            <el-button
              size="small"
              plain
              class="button_edit"
              @click="addProjectHandler"
              ><svg-icon icon-class="add-icon-1" class="m-r5" /> 添加</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="deleteHandle"
              class="button_edit"
              >删除</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="pushProjectType"
              class="button_edit"
              >项目分类设置</el-button
            >
            <el-button
              size="small"
              plain
              class="button_edit"
              @click="
                onExport({
                  ...getSearchData(),
                  type: state.tabId,
                  prepareStatus: -1,
                })
              "
              ><svg-icon icon-class="export" class="m-r5" />一键导出</el-button
            >
          </div>
        </template>

        <template #operate>
          <el-table-column label="操作" width="500" fixed="right">
            <template #default="{ row }">
              <!--							<el-button
									v-if="state.tabId === '1' && row.meetingApplyStatus === 2 && row.projectTypeId==='1'"
									size="small"
									class="button_funtion m-b10 m-l0 m-r10"
									type="primary"
									@click="investmentPlan(row)"
							>投资方案</el-button
							>-->
              <el-button
                v-if="state.tabId !== '1'"
                size="small"
                class="button_view m-b10 m-l0 m-r10"
                type="primary"
                @click="projectStageHandler(row)"
                >项目规划</el-button
              >
              <el-button
                size="small"
                class="button_cancel m-b10 m-l0 m-r10"
                type="primary"
                @click="editProjectHandler(row)"
                >项目信息</el-button
              >
              <el-button
                v-if="
                  (row.meetingApplyStatus == 0 && row.isGovernment != 1) ||
                  (row.meetingApplyStatus == 3 && row.isGovernment != 1)
                "
                size="small"
                type="primary"
                class="button_funtion m-b10 m-l0 m-r10"
                @click="projectProposal(row, '发起')"
                >发起议题请示</el-button
              >
              <el-button
                v-if="row.meetingApplyStatus > 0"
                size="small"
                type="primary"
                class="button_view m-b10 m-l0 m-r10"
                @click="projectProposal(row, '查看')"
                >查看议题请示详情</el-button
              >
              <!--							v-if="row.meetingApplyStatus === 2 && ((row.planStatus === 2 && row.projectTypeId==='1')|| row.projectTypeId !=='1')"-->
              <el-button
                v-if="row.meetingApplyStatus === 2"
                size="small"
                type="primary"
                class="button_funtion m-b10 m-l0"
                @click="projectApprove(row, '上报')"
                >上报请示决策会议</el-button
              >

              <el-button
                v-if="
                  (state.tabId === '3' || state.tabId === '2') &&
                  row.isGovernment === 1
                "
                size="small"
                type="primary"
                class="button_view m-b10 m-l0 m-r10"
                @click="toProjectApprovalInformation(row)"
                >上传立项信息</el-button
              >
            </template>
          </el-table-column>
        </template>
      </tableIndex>

      <!-- 立项议题 -->
      <preliminaryCom
        :type="state.tabId"
        ref="preliminary"
        @refreshList="getPage"
      />

      <!--	项目阶段-->
      <projectStage ref="projectstage" />

      <!-- 立项审批单 -->
      <preliminaryspDialog ref="preliminarysp" />

      <!--	投资方案		-->
      <add-investment-projects
        ref="addInvestmentProjectsRef"
        title="投资方案"
        v-model:visible="addInvestmentProjectsVisible"
        @on-success="onSuccess"
        @departmentChange="departmentChange"
      />
    </div>
  </div>
</template>
<script setup>
import "@/views/constructionProjectManage/static/button.scss";
import TableIndex from "@/components/table/index.vue";
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  onBeforeMount,
  watch,
  provide,
} from "vue";
import PreliminaryCom from "./components/preliminaryDialog.vue";
import ProjectStage from "./components/projectPhaseDialog.vue";
import PreliminaryspDialog from "./components/preliminaryspDialog.vue";
import AddInvestmentProjects from "./components/addInvestmentProjects.vue";

import {
  ElDialog,
  ElTabPane,
  ElTabs,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { projectConfigApi, publicProject, department } from "@/api/project.js";
import { deriveHandelFnc } from "@/hooks/downCommon";
import { assetsApi } from "@/api/assets";
import {
  otherApi,
  projectSetApi,
  reserveInvestmentProjectLibraryApi,
} from "@/api/investment";
import { localGet, localSet } from "@/common/utils/GlobalUtils";

//路由跳转
let router = useRouter();
let tableRef = ref(null);
let activeName = reactive("0");
let preliminary = ref(null);
let projectstage = ref(null);
let preliminarysp = ref(null);
let data = reactive([]);
let state = reactive({
  tabId: "1",
  tabName: "departmentName",
  loading: true,
  fields: [
    {
      key: "projectQuery",
      label: "项目名称",
      type: "input",
      placeholder: "根据项目集名称或编码搜索",
    },
    {
      key: "projectSetId",
      label: "关联项目集",
      type: "select",
      options: {
        list: [],
      },
    },
    {
      key: "streetCode",
      label: "项目位置",
      type: "select",
      options: {
        list: [],
      },
    },
    {
      key: "departmentId",
      label: "立项部门",
      type: "select",
      options: {
        list: [],
      },
    },
  ],
  projectType: [],
  industryList: [],
  partnerList: [],
  companyList: [],
  selectedList: [],
  allDepartmentList: [],
  departmentPersonList: [],
  projectSetList: [],
  row: null,
  title: "新增",
});

provide("state", state);

const formInline = reactive({
  user: "",
  region: "",
  date: [],
  radio: 0,
});
// tabs相关
const tabsList = ref([
  {
    name: "投资类",
    id: "1",
  },
  {
    name: "设计类",
    id: "2",
  },
  {
    name: "开发类",
    id: "3",
  },
  {
    name: "运营类",
    id: "4",
  },
  {
    name: "公共类",
    id: "5",
  },
]);

watch(
  () => state.tabId,
  (val) => {
    getPage(tableRef.value.getSearchData());
  }
);

const page = reactive({
  page: 1,
  pageSize: 50,
  total: 0,
});
const selectList = ref([]);
const selectChange = (e) => {
  selectList.value = e;
};

// --------------
// table相关
let tableHead = reactive([
  {
    prop: "projectSetName",
    label: "关联项目集",
    width: "120",
  },
  {
    prop: "projectName",
    label: "项目名称",
    width: "120",
    style: {
      color: "#FC7018",
    },
  },
  // {
  // 	prop: "projectId",
  // 	label: "项目编号",
  // 	width: "250",
  // },
  {
    prop: "projectTypeName",
    label: "项目分类",
    width: "120",
  },
  {
    prop: "isGovernment",
    label: "政府项目",
    formatter: (row) => {
      if (row.isGovernment !== null) {
        return ["否", "是"][row.isGovernment];
      }
      return "-";
    },
  },
  {
    prop: "streetName",
    label: "项目位置",
    width: "120",
  },
  {
    prop: "responsibleDepartmentName",
    label: "项目立项部门",
    width: "140",
  },
  {
    prop: "projectAmount",
    label: "拟计划总投额",
    width: "140",
  },
  {
    prop: "createTime",
    label: "项目创建时间",
    width: "200",
  },
]);
let tableData = ref([]);
const projectProposal = (row, type) => {
  preliminary.value.state.type = type;
  preliminary.value.state.disabled = false;
  if (type === "查看") {
    preliminary.value.state.disabled = true;
    preliminary.value.state.type = type;
  }
  preliminary.value.state.centerDialogVisible = true;
  preliminary.value.state.projectId = row.projectId;
  preliminary.value.state.projectTypeId = row.projectTypeId;
  preliminary.value.state.tabId = state.tabId;
  preliminary.value.getBfProjectSubjectMeetingView(row);
};

//项目阶段
const projectStageHandler = (row) => {
  console.log("row", row);
  projectstage.value.state.centerDialogVisible = true;
  projectstage.value.state.projectTypeId = row.projectTypeId;
  projectstage.value.state.projectId = row.projectId;
  projectstage.value.state.tabId = state.tabId;
  // row.meetingApplyStatus==0||row.meetingApplyStatus==3
  projectstage.value.state.meetingApplyStatus = row.meetingApplyStatus;
  projectstage.value.state.startTime = row.predictStartTime;
  projectstage.value.state.endTime = row.predictEndTime;
};
//立项审批
const projectApprove = (row, type) => {
  preliminarysp.value.state.disabled = false;
  preliminarysp.value.state.type = type;
  preliminarysp.value.state.tabId = state.tabId;
  preliminarysp.value.state.centerDialogVisible = true;
  preliminarysp.value.getBfbfProjectApprovalFormView(row);
};

/**
 * 跳转"上传立项信息"页
 */
const toProjectApprovalInformation = (row) => {
  router.push({
    path: `/constructionProjectManage/preliminaryProject/uploadProjectApprovalInfo/${row.projectId}`,
  });
};

//项目阶段添加
const addProjectHandler = () => {
  switch (state.tabId) {
    case "1":
      router.push(
        `/constructionProjectManage/preliminaryProject/components/preliminaryInfo2/type=0&projectId=${""}&projectType=${
          state.tabId
        }`
      );
      break;
    default:
      router.push(
        `/constructionProjectManage/preliminaryProject/components/preliminaryInfo/type=0&projectId=${""}&projectType=${
          state.tabId
        }`
      );
      break;
  }
};
//项目阶段修改
const editProjectHandler = (row) => {
  if (state.tabId === "1") {
    router.push(
      `/constructionProjectManage/preliminaryProject/components/preliminaryInfo2/type=1&projectTypeId=${row.projectTypeId}&projectId=${row.projectId}&projectType=${state.tabId}`
    );
  } else {
    router.push(
      `/constructionProjectManage/preliminaryProject/components/preliminaryInfo/type=1&projectTypeId=${row.projectTypeId}&projectId=${row.projectId}&projectType=${state.tabId}`
    );
  }
};
//项目查看
const lookHandler = (row) => {
  router.push(
    `/constructionProjectManage/projectmanagement/lookindex/type=1&projectId=${row.projectId}&projectName=${row.projectName}`
  );
};
// 获取项目集
const getpublicProject = () => {
  projectConfigApi.getProjectSets().then((res) => {
    if (res.code == 200) {
      res.data.forEach((item) => {
        state.fields[1].options.list.push({
          label: item.projectSetName,
          value: item.projectSetId,
        });
      });
      state.fields[1].options.list.unshift({
        label: "全部",
        value: "",
      });
    }
  });
};
// 获取部门
const getAllDepartments = () => {
  department.getAllDepartments().then((res) => {
    if (res.code === "200") {
      state.allDepartmentList = res.data;
      res.data.forEach((item) => {
        state.fields[3].options.list.push({
          label: item.departmentName,
          value: item.departmentId,
        });
      });
      state.fields[3].options.list.unshift({
        label: "全部",
        value: "",
      });
      console.log("state.fields[3]", state.fields[3]);
    }
  });
};
const deleteHandle = () => {
  if (selectList.value.length == 0) {
    return ElMessage.warning("请选择要删除的数据");
  }

  ElMessageBox.confirm("确认删除吗?", {
    confirmButtonText: "确认",
    confirmButtonClass: "button_view",
    cancelButtonText: "取消",
    cancelButtonClass: "button_cancel2",
    type: "warning",
  })
    .then(() => {
      projectConfigApi
        .prepareRemove(selectList.value[0].projectId || "")
        .then((res) => {
          if (res.code === "200") {
            ElMessage.success("删除成功");
            getPage();
          }
        });
    })
    .catch(() => {});
};
const pushProjectType = () => {
  router.push(`/constructionProjectManage/taskNotification/classification`);
};
//搜索查询
const searchList = (e) => {
  getPage(e);
};
//分页
const pageChange = (e) => {
  page.page = e.page;
  page.pageSize = e.limit;

  getPage();
};

const getPage = (e) => {
  let data = {
    pageNum: page.page,
    pageSize: page.pageSize,
    param: {
      ...e,
      prepareStatus: -1,
      type: state.tabId,
      ...getSearchData(),
    },
  };

  projectConfigApi.getProjectPage(data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.data.content;
      page.total = res.data.totalSize;
      console.log(tableData);
    }
  });
};

//获取部门信息
const getdepartmentList = () => {
  department.getProjectPhase().then((res) => {
    if (res.code === "200") {
      data = res.data;
      state.loading = false;
    }
  });
};
//获取阶段
const initAreaOptions = (type = "2", cd = "") => {
  // type：1-获取区域 ；2-获取街道
  // cd：获取区域时不传
  assetsApi.getLocations(type, cd).then((res) => {
    const { code, data, msg } = res;
    if (code == 200) {
      res.data.forEach((item) => {
        item.label = item.name;
        item.value = item.code;
      });
      state.fields[2].options.list = res.data;
      state.fields[2].options.list.unshift({ label: "全部", value: "" });
    }
  });
};
//获取搜索组件数据
const getSearchData = () => {
  return tableRef.value.getSearchData();
};
//获取项目类型
const publicProjectData = () => {
  publicProject.getProjectTypeTreeVo().then((res) => {
    if (res.code == 200) {
      data = res.data;
      state.loading = false;
    }
  });
};

const exportConfig = reactive({
  fileName: "预备项目管理",
  apiPath: "projectExport",
  form: {},
});

/**
 * 投资方案
 */
const addInvestmentProjectsRef = ref(null);
const investmentPlan = (row) => {
  addInvestmentProjectsVisible.value = true;
  addInvestmentProjectsRef.value.getStatus(row.projectId);
};

const addInvestmentProjectsVisible = ref(false);
const onSuccess = () => {};
const departmentChange = () => {};

/**
 * 获取下拉框
 */
const getListEnum = (type) => {
  otherApi.getListEnum({ type: type }).then((res) => {
    const { code, data } = res;
    if (code == 200) {
      type == 1 ? (state.projectType = data) : (state.industryList = data);
    }
  });
};

/**
 * 合作方
 */
const getAllPartner = () => {
  reserveInvestmentProjectLibraryApi.getAllPartner().then((res) => {
    const { code, data } = res;
    if (code == 200) {
      state.partnerList = data;
    }
  });
};

/**
 * 实施主体
 */
const getCompanyList = () => {
  otherApi.getCompanyList({}).then((res) => {
    const { code, data } = res;
    if (code == 200) {
      state.companyList = data;
    }
  });
};

const selected = (id) => {
  localSet("tabId", id.toString());
  state.tabId = id;
};

const { onExport } = deriveHandelFnc(exportConfig);

onMounted(() => {
  getdepartmentList();
  initAreaOptions();
  getAllPartner();
  getPage();
  getpublicProject();
  getAllDepartments();
  if (localGet("tabId")) {
    state.tabId = localGet("tabId").toString();
  }
});
</script>
<style lang="scss" scoped>
.tabsClass {
  .tabBox {
    width: 100%;
  }
}
.tabsBox {
  margin-bottom: 30px;
  .tabsItem {
    padding: 0 30px;
    text-align: center;
    line-height: 40px;
    height: 40px;
    border: 1px solid #ccc;
    margin-right: 20px;
    border-radius: 5px;
    color: #ccc;
    cursor: pointer;
  }
  .tabsItemHover {
    border: 1px solid #fc702b;
    color: #fc702b;
    background: #fff8f6;
  }
}
</style>
